#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024
#define RSIZE 4

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int client_sock;
    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error!");
    }
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        error_handling("connect() error!");
    } else {
        puts("connecting.......");
    }

    // 1B num  
    // 4nB interger 
    // 1B op 
    // 4B res
    char buf[BUFSIZE];
    memset(buf, 0, sizeof buf);
    printf("please input number\n");
    int num;
    scanf("%d", &num);
    buf[0] = (char)num;
    printf("cnt = %d\n", num);
    for (int i = 0; i < num; i++)  {
        scanf("%d", (int*)(buf + 1 + i * 4));
        printf(" %d \n", *(buf + 1 + i * 4));
    }
    getchar();
    printf("please input operator\n");
    scanf("%c", buf + 1 + num * 4);
    printf("op = %c\n", buf[1 + num * 4]);
    int str_len = write(client_sock, buf, BUFSIZE - 1);
    if (str_len == -1) {
        error_handling("write error!\n");
    }
    int res;
    if ((read(client_sock, &res, RSIZE)) == -1) {
        error_handling("read error\n");
    } else {
        printf("res = %d\n", res);
    }
    close(client_sock);
    return 0;
}